package com.caishi.lkx.user.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.user.model.GroupModel;
import com.caishi.lkx.user.model.re.SysGroupLocationReModel;
import com.caishi.lkx.user.service.IGroupLocationReService;
import com.caishi.lkx.user.service.IGroupService;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.impl.BaseIntEntity;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "机构ip经纬度绑定")
@RestController
@RequestMapping("/user/sys/group/location")
public class GroupLocationReApi extends AdminBaseApi<IGroupLocationReService, SysGroupLocationReModel, Long> {
    @Resource
    private IGroupLocationReService groupLocationReService;
    @Resource
    private IGroupService groupService;
    @Resource
    private IUserService userService;

    @Override
    public IGroupLocationReService loadService() {
        return groupLocationReService;
    }

    @Override
    protected LambdaQueryWrapper<SysGroupLocationReModel> baseWrapper(SysGroupLocationReModel model, JSONObject otherParam) {
        List<Long> groupIds = null;
        String groupName = otherParam.getStr("groupName", "");
        String expireTime = otherParam.getStr("expireTime", "");
        String bindDay = otherParam.getStr("bindDay", "");
        if(StrUtil.isNotBlank(groupName) || StrUtil.isNotBlank(expireTime)){
            groupIds = groupService.selectList(Wrappers.<GroupModel>lambdaQuery().select(GroupModel::getId)
                    .like(StrUtil.isNotBlank(groupName), GroupModel::getName, groupName))
                    ///.eq(StrUtil.isNotBlank(expireTime),GroupModel::getExpireTime, expireTime))
                    .stream().map(BaseIntEntity::getId).collect(Collectors.toList());
            if (CollUtil.isEmpty(groupIds)){
                groupIds.add(-1L);
            }
        }
        return Wrappers.lambdaQuery(model.clearEmptyStringField())
                .in(CollUtil.isNotEmpty(groupIds),SysGroupLocationReModel::getGroupId,groupIds)
                .likeRight(StrUtil.isNotBlank(bindDay),SysGroupLocationReModel::getBindTime,bindDay);
    }

    @GetMapping("/check")
    public void checkLocationExist(@RequestParam String locationStr) {
        String[] split = locationStr.split("-");
        groupLocationReService.checkExist(new BigDecimal(split[0].trim()), new BigDecimal(split[1].trim()),null);
    }
    @GetMapping("/batch-check")
    public Map<String,Object> batchCheckLocationExist(@RequestParam String locationStr) {

      return   groupLocationReService.batchCheckLocationExist(locationStr);
    }

    @Override
    protected List<SysGroupLocationReModel> listCover(List<SysGroupLocationReModel> result, JSONObject otherParam) {
     return    result.parallelStream().peek(r ->{
            if(null != r.getGroupId()){
                GroupModel group = groupService.getById(r.getGroupId());
                if(null != group){
                r.setGroupName(group.getName());
                //r.setExpireTime(group.getExpireTime());
                }
            }
            if(StrUtil.isNotBlank(r.getBindUserId())){
                r.setBindUserName(userService.queryName(r.getBindUserId()));
            }
        }).collect(Collectors.toList());
    }

    @Override
    @PostMapping("/update")
    @Operation(summary = "添加")
    public SysGroupLocationReModel add(SysGroupLocationReModel entity) {
        groupLocationReService.checkExist(entity.getLongitude(), entity.getLatitude(),null);
        entity.setBindTime(LocalDateTime.now());
        entity.setBindUserId(userContext.currentUserId());
        return groupLocationReService.insert(entity);
    }
    @PostMapping("/batchAdd")
    @Operation(summary = "添加")
    public Boolean batchAdd(@RequestParam Long groupId,@RequestParam List<String> locationList,String remark) {
        String userId = userContext.currentUserId();
        LocalDateTime now = LocalDateTime.now();
        locationList.parallelStream().forEach(p -> {
            String[] split = p.split("-");
            SysGroupLocationReModel entity = new SysGroupLocationReModel();
            entity.setGroupId(groupId);
            entity.setBindTime(now);
            entity.setBindUserId(userId);
            entity.setLongitude(new BigDecimal(split[0]));
            entity.setLatitude(new BigDecimal(split[1]));
            entity.setRemark(remark);
            groupLocationReService.insert(entity);
        });
        return true;
    }

    @Override
    @PutMapping("/update")
    public SysGroupLocationReModel update(SysGroupLocationReModel entity) {
        groupLocationReService.checkExist(entity.getLongitude(), entity.getLatitude(), entity.getId());
        return groupLocationReService.simpleUpdate(entity);
    }

    @PutMapping("/reBind")
    @Operation(summary = "重新绑定")
    public Boolean reBind(@RequestParam Long id, @RequestParam Long groupId) {

        return groupLocationReService.reBind(id, groupId, userContext.currentUserId());
    }

    @PutMapping("/unBind")
    @Operation(summary = "取消绑定")
    public Boolean unBind(@RequestParam Long id) {

        return groupLocationReService.unBind(id,userContext.currentUserId());
    }
}
